﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Fetches.Fetch.Utils
{
    public static class HashHelper
    {
        public static string Sha1(string str)
        {
            return Hash(str, new SHA1CryptoServiceProvider());
        }

        public static string Sha1(byte[] data)
        {
            return Hash(data, new SHA1CryptoServiceProvider());
        }

        public static string Md5(string str)
        {
            return Hash(str, new MD5CryptoServiceProvider());
        }

        public static string Md5(byte[] data)
        {
            return Hash(data, new MD5CryptoServiceProvider());
        }

        private static string Hash(string str, HashAlgorithm provider)
        {
            return Hash(Encoding.UTF8.GetBytes(str), provider);
        }

        private static string Hash(byte[] data, HashAlgorithm provider)
        {
            string strResult = "";
            try
            {
                byte[] arrbytHashValue = provider.ComputeHash(data); //计算指定Stream 对象的哈希值

                //由以连字符分隔的十六进制对构成的String，其中每一对表示value 中对应的元素；例如“F-2C-4A”
                string strHashData = BitConverter.ToString(arrbytHashValue); //,4,8去掉4,8为40位

                strHashData = strHashData.Replace("-", ""); //替换-
                strResult = strHashData;
            }

            catch (Exception)
            {
                return "";
            }
            return strResult;
        }
    }
}
